<?php
/**
 * Created by PhpStorm.
 * User: xsp
 * Date: 2018/4/16
 * Time: 20:39
 */

namespace backend\models;

use yii\db\ActiveRecord;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\mail\BaseMailer;
use yii;
class  Admin extends ActiveRecord implements yii\web\IdentityInterface
{

    public $rememberMe = true;
    public $checkpass ;
    public function rules()
    {
        return [
            ['adminuser', 'required', 'message' => '账号不能为空','on'=>['seekPass','login','changePass','addManager']],
            ['adminpass', 'required', 'message' => '密码不能为空','on'=>['login','changePass','addManager']],
            ['adminuser','unique', 'targetClass' => '\backend\models\Admin', 'message' => '用户名已存在.','on'=>'addManager'],
            ['rememberMe', 'boolean','on'=>'login'],
            ['adminemail', 'unique', 'targetClass' => '\backend\models\Admin', 'message' => 'email已经被设置了.','on'=>'addManager'],
            ['adminpass', 'validatePass','message'=>'用户名或密码错误','on'=>'login'],
            ['adminemail','required','message'=>'邮箱不能为空','on'=>['seekPass','addManager']],
            ['adminemail','email','message'=>'邮箱格式不正确','on'=>['seekPass','addManager']],
            ['adminemail','validateEmail','on'=>'seekPass'],
            ['checkpass','compare','compareAttribute'=>'adminpass','message'=>'两次密码不一致','on'=>['changePass','addManager']],
            ['checkpass','required','message'=>'确认密码不能为空','on'=>['changePass','addManager']],
            [['logintime','createtime'],'safe']
        ];
    }
    public static function findIdentity($id)
    {
        return static::findOne($id);
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['access_token' => $token]);
    }

    public function getId()
    {
        return $this->adminid;
    }

    public function getAuthKey()
    {
        return $this->authKey;
    }

    public function validateAuthKey($authKey)
    {
        return $this->authKey === $authKey;
    }
    public function validatepass()
    {
        if (!$this->hasErrors()) {
            $data = self::find()->where(['adminuser' => $this->adminuser, 'adminpass' => md5($this->adminpass)])->one();

            if (is_null($data)) {
                $this->addError('adminpass','用户名或密码错误');
            }
        }
    }
    public function validateEmail()
    {
        if(!$this->hasErrors())
        {
            $data = self::find()->where(['adminuser'=>$this->adminuser,'adminemail'=>$this->adminemail])->one();
            if(is_null($data))
            {
                $this->addError('adminemail','账号或邮箱不正确');
            }
        }
    }
    public function getUser()
    {
        return self::find()->where(['adminuser'=>$this->adminuser])->one();
    }
    public function login($data)
    {
        $this->scenario = "login";
        if($this->load($data)&&$this->validate()) {
            $this->updateAll(['logintime'=>time(),'loginip'=>ip2long("127.0.0.1")],['adminuser'=>$this->adminuser]);
            return Yii::$app->admin->login($this->getUser(),3600*60);
        }
            return false;
    }
    public function seekPass($post)
    {
        $this->scenario = "seekPass";
        if($this->load($post)&&$this->validate())
        {
        $time = time();
        $adminuser = $post['Admin']['adminuser'];
        $token  = $this->createToken($post['Admin']['adminuser'],$time);
        $mailer = \Yii::$app->mailer->compose('seekpass',['text'=>'text','adminuser'=>$post['Admin']['adminuser'],'token'=>$_SERVER['HTTP_HOST'].Url::toRoute(['manage/emailchangepass'])."&timestamp=".$time."&token=".$token."&adminuser=".$adminuser]);
            $mailer ->setFrom("1115007981@qq.com")
                    ->setTo("1115007981@qq.com")
                    ->setSubject("黑势力科技")
                    ->send();
        if($mailer)
            return true;
        }

        return false;
    }
    public function  createToken($adminuser,$time)
    {

        return md5(md5($adminuser).base64_encode(\Yii::$app->request->userIP).md5($time));
    }
    public function changepass($post)
    {

        $this->scenario = "changePass";
        if($this->load($post)&&$this->validate())
        {
             return (bool)$this->updateAll(['adminpass'=>md5($this->adminpass)],['adminuser'=>$this->adminuser]);

        }
        return false;
    }
    public function  Addmanager($data)
    {
        $this->scenario = "addManager";

        if($this->load($data)&&$this->validate())
        {
            $data['Admin']['adminpass'] = md5( $data['Admin']['adminpass'] );
            $data['Admin']['checkpass'] = md5( $data['Admin']['checkpass'] );
            $data['Admin']['createtime'] = time();
            $data['Admin']['logintime'] = time();
            if($this->save(false))
            return true;
        }
        return false;
    }

}